<template>
  <div>
    <t-card class="list-card-container">
      <t-row justify="space-between">
        <div class="left-operation-container">
          <t-button @click="refresh"> 刷新 </t-button>
          <!-- <t-button variant="base" theme="default" :disabled="!selectedRowKeys.length"> 导出合同 </t-button> -->
          <p v-if="!!selectedRowKeys.length" class="selected-count">已选{{ selectedRowKeys.length }}项</p>
        </div>
        <div class="search-input">
          <!-- <t-input v-model="searchValue" placeholder="请输入你需要搜索的内容" clearable>
            <template #suffix-icon>
              <search-icon size="20px" />
            </template>
          </t-input> -->
          <t-date-range-picker allow-input clearable :presets="presets" @pick="onPick" @change="onPickChange" />
        </div>
      </t-row>
      <t-table
        :data="data"
        :columns="COLUMNS"
        :row-key="rowKey"
        vertical-align="top"
        :hover="true"
        :pagination="pagination"
        :selected-row-keys="selectedRowKeys"
        :loading="dataLoading"
        :header-affixed-top="{ offsetTop, container: getContainer }"
        @page-change="rehandlePageChange"
        @change="rehandleChange"
        @select-change="rehandleSelectChange"
      >
        <template #status="{ row }">
          <t-tag v-if="row.status === CONTRACT_STATUS.FAIL" theme="danger" variant="light"> 审核失败 </t-tag>
          <t-tag v-if="row.status === CONTRACT_STATUS.AUDIT_PENDING" theme="warning" variant="light"> 待审核 </t-tag>
          <t-tag v-if="row.status === CONTRACT_STATUS.EXEC_PENDING" theme="warning" variant="light"> 待履行 </t-tag>
          <t-tag v-if="row.status === CONTRACT_STATUS.EXECUTING" theme="success" variant="light"> 履行中 </t-tag>
          <t-tag v-if="row.status === CONTRACT_STATUS.FINISH" theme="success" variant="light"> 已完成 </t-tag>
        </template>
        <template #refundChannel="{ row }">
          <p v-if="row.refundChannel === 0">未知</p>
          <p v-if="row.refundChannel === 1">微信支付</p>
          <p v-if="row.refundChannel === 2">支付宝</p>
        </template>
        <template #paymentType="{ row }">
          <div v-if="row.paymentType === CONTRACT_PAYMENT_TYPES.PAYMENT" class="payment-col">
            付款<trend class="dashboard-item-trend" type="up" />
          </div>
          <div v-if="row.paymentType === CONTRACT_PAYMENT_TYPES.RECEIPT" class="payment-col">
            收款<trend class="dashboard-item-trend" type="down" />
          </div>
        </template>

        <template #op="slotProps">
          <a class="t-button-link" @click="handleClickDetail(slotProps)">详情</a>
          <!-- <a class="t-button-link" @click="handleClickDelete(slotProps)">删除</a> -->
        </template>
      </t-table>
    </t-card>

    <t-dialog
      v-model:visible="confirmVisible"
      header="确认删除当前所选？"
      :body="confirmBody"
      :on-cancel="onCancel"
      @confirm="onConfirmDelete"
    />

    <t-drawer v-model:visible="drawerVisible" size="large" header="详情" :footer="null">
      <t-form ref="form" :data="formData">
        <t-form-item label="createDate" name="createDate">
          <label>{{ formData.createDate }}</label>
        </t-form-item>
        <t-form-item label="refundNo" name="refundNo">
          <label>{{ formData.refundNo }}</label>
        </t-form-item>
        <t-form-item label="refundAmount" name="refundAmount">
          <label>{{ formData.refundAmount }}</label>
        </t-form-item>
        <t-form-item label="originOrderNo" name="originOrderNo">
          <label>{{ formData.originOrderNo }}</label>
        </t-form-item>
        <t-form-item label="tradeSerialNo" name="tradeSerialNo">
          <label>{{ formData.tradeSerialNo }}</label>
        </t-form-item>
        <t-form-item label="refundId" name="refundId">
          <label>{{ formData.refundId }}</label>
        </t-form-item>
        <t-form-item label="refundDate" name="refundDate">
          <label>{{ formData.refundDate }}</label>
        </t-form-item>
        <t-form-item label="originUserId" name="originUserId">
          <label>{{ formData.originUserId }}</label>
        </t-form-item>
        <t-form-item label="appId" name="appId">
          <label>{{ formData.appId }}</label>
        </t-form-item>
        <t-form-item label="mchId" name="mchId">
          <label>{{ formData.mchId }}</label>
        </t-form-item>
        <t-form-item label="refundChannel" name="refundChannel">
          <label>{{ formData.refundChannel }}</label>
        </t-form-item>
      </t-form>
    </t-drawer>
  </div>
</template>

<script lang="ts">
export default {
  name: 'RefundOrderList',
};
</script>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';

import { MessagePlugin } from 'tdesign-vue-next';

import dayjs from 'dayjs';
import { CONTRACT_STATUS, CONTRACT_PAYMENT_TYPES } from '@/constants';
import Trend from '@/components/trend/index.vue';
import { getList } from '@/api/refund';
import { useSettingStore } from '@/store';
import { prefix } from '@/config/global';

import { COLUMNS } from './constants';

const presets = ref({
  最近7天: [dayjs().subtract(6, 'day'), dayjs()],
  最近3天: [dayjs().subtract(2, 'day'), dayjs()],
  今天: [dayjs(), dayjs()],
});

const store = useSettingStore();

const data = ref([]);
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  date: '',
  mchId: '',
});

const drawerVisible = ref(false);
const dataLoading = ref(false);
const refresh = async () => {
  await fetchData();
};
const fetchData = async () => {
  dataLoading.value = true;
  try {
    const { items, totalItems, currentPage } = await getList(pagination);
    data.value = items;
    pagination.date = '';
    pagination.mchId = '';
    pagination.current = currentPage;
    pagination.total = totalItems;
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};
const deleteIdx = ref(-1);
const confirmBody = computed(() => {
  if (deleteIdx.value > -1) {
    const { name } = data.value[deleteIdx.value];
    return `删除后，${name}的所有信息将被清空，且无法恢复`;
  }
  return '';
});
onMounted(async () => {
  await fetchData();
});

const confirmVisible = ref(false);
const selectedRowKeys = ref([]);

const resetIdx = () => {
  deleteIdx.value = -1;
};

const onConfirmDelete = () => {
  // 真实业务请发起请求
  confirmVisible.value = false;
  MessagePlugin.success('删除成功');
};

const onCancel = () => {
  resetIdx();
};

const rowKey = 'index';

const rehandleSelectChange = (val: number[]) => {
  selectedRowKeys.value = val;
};
const rehandlePageChange = (curr, pageInfo) => {
  console.log('分页变化', curr, pageInfo);
};
const rehandleChange = (changeParams, triggerAndData) => {
  console.log('统一Change', changeParams, triggerAndData);
};
// 详情
const formData = reactive({
  createDate: '',
  refundNo: '',
  refundAmount: '',
  originOrderNo: '',
  tradeSerialNo: '',
  refundId: '',
  refundDate: '',
  originUserId: '',
  appId: '',
  mchId: '',
  refundChannel: '',
});
const handleClickDetail = (obj: any) => {
  drawerVisible.value = true;
  formData.createDate = obj.row.createDate;
  formData.refundNo = obj.row.refundNo;
  formData.createDate = obj.row.createDate;
  formData.refundAmount = obj.row.refundAmount;
  formData.originOrderNo = obj.row.originOrderNo;
  formData.tradeSerialNo = obj.row.tradeSerialNo;
  formData.refundId = obj.row.refundId;
  formData.refundDate = obj.row.refundDate;
  formData.originUserId = obj.row.originUserId;
  formData.appId = obj.row.appId;
  formData.mchId = obj.row.mchId;
  formData.refundChannel = obj.row.refundChannel;
};

const handleClickDelete = (row: { rowIndex: any }) => {
  deleteIdx.value = row.rowIndex;
  confirmVisible.value = true;
};

const offsetTop = computed(() => {
  return store.isUseTabsRouter ? 48 : 0;
});

const getContainer = () => {
  return document.querySelector(`.${prefix}-layout`);
};

// 日期选择
const onPick = (value, context) => console.log('onPick:', value, context);
const onPickChange = (value, context) => {
  console.log('onPickChange:', value, context);

  pagination.date = `${value[0]},${value[1]}`;
  fetchData();
  console.log(
    'YYYYMMDD:',
    context.dayjsValue.map((d) => d.format('YYYYMMDD')),
  );
};
</script>

<style lang="less" scoped>
.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: 8px;
  }
}

.left-operation-container {
  padding: 6px 0;
  margin-bottom: 16px;

  .selected-count {
    display: inline-block;
    margin-left: 8px;
    color: var(--td-text-color-secondary);
  }
}

.search-input {
  width: 360px;
}
</style>
